package duplexpipe.sni;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentMap;

public class TCPListener implements Runnable {
	
	private int port;
	public  TCPListener(int port) {
		this.port = port;
	}
	
	private ConcurrentMap<String, Socket> map;
	
	
	public ConcurrentMap<String, Socket> getMap() {
		return map;
	}

	public void setMap(ConcurrentMap<String, Socket> map) {
		this.map = map;
	}

	private Socket socket;
	
	@Override
	public void run() {
		ServerSocket ss;
		try {
			ss = new ServerSocket (port, 1);
			//ss.setSoTimeout(0);
			
			while (true) {
				socket = ss.accept ();
				socket.setKeepAlive(true);
				//socket.setOOBInline(true);
				//socket.setSoTimeout(1000 *5);
				if (map != null)
				{
					if (map.size() > 1000)  { socket.close(); }
					map.put(CommonUtil.getAddrAndPort(socket, "L") , socket);
					
				}else {
					try {
						connecterQueue.put(socket);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
			
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	
		
	}
	
	public BlockingQueue<Socket> getConnecterQueue() {
		return connecterQueue;
	}



	public void setConnecterQueue(BlockingQueue<Socket> connecterQueue) {
		this.connecterQueue = connecterQueue;
	}


	
	private BlockingQueue<Socket> connecterQueue;
	
	
}
